package com.common.app.utls

import android.annotation.SuppressLint
import android.os.Build
import android.text.TextUtils
import com.common.app.R
import com.common.app.data.bean.TimeComponents
import com.common.base.app.extras.no
import com.common.base.app.extras.yes
import com.common.base.utils.AppUtils
import com.common.base.utils.AppUtils.getString
import com.common.base.utils.AppUtils.toInt
import java.text.ParseException
import java.text.SimpleDateFormat
import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter
import java.util.*
import java.util.concurrent.TimeUnit
import kotlin.math.abs


/**
 *
 * 时间工具类
 */
@SuppressLint("ConstantLocale")
object TimeUtils {

    val formatYearMonthDay = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
    val formatYearMonthDaySeries = SimpleDateFormat("yyyyMMdd", Locale.getDefault())
    val formatYearMonthDay2 = SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.getDefault())
    val formatYearMonthDay4 = SimpleDateFormat("yyyy.MM.dd HH:mm", Locale.getDefault())
    val formatYearMonthDay5 = SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault())
    val formatYearMonthDayHHmm = SimpleDateFormat("MM月dd日 HH:mm", Locale.getDefault())
    val formatYearMonthDayHour = SimpleDateFormat("yyyy-MM-dd HH", Locale.getDefault())
    val formatYearMonthDayHourMin = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())
    val formatYearMonthDayHourMinSecond =
        SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
    val formatMonth = SimpleDateFormat("MM", Locale.getDefault())
    val formatYear = SimpleDateFormat("yyyy", Locale.getDefault())
    val formatYearMonth = SimpleDateFormat("yyyy-MM", Locale.getDefault())
    val formatYearMonth2 = SimpleDateFormat("yyyy/MM", Locale.getDefault())
    val formatYearMonthDay_ = SimpleDateFormat("yyyy/MM/dd", Locale.getDefault())
    val formatYearMonthDay3 = SimpleDateFormat("yy/MM/dd", Locale.getDefault())
    val formatMonthDay = SimpleDateFormat("M月d日", Locale.getDefault())
    val formatMonthDayDefault = SimpleDateFormat("MM月dd日", Locale.getDefault())
    val formatYearMonthDefault = SimpleDateFormat("yyyy年MM月", Locale.getDefault())
    private val formatMonthDay_ = SimpleDateFormat("MM/dd", Locale.getDefault())
    val formatMonthDayFoot = SimpleDateFormat("MM/dd", Locale.getDefault())
    val formatHourMinute = SimpleDateFormat("HH:mm", Locale.getDefault())
    val formatHourMinuteSecond = SimpleDateFormat("HH:mm:ss", Locale.getDefault())
    val formatMonthDayHourMinute = SimpleDateFormat("MM-dd HH:mm", Locale.getDefault())
    val formatMonthDayHourMinuteDetail = SimpleDateFormat("MM/dd HH:mm", Locale.getDefault())
    private val formatMonthDayMMdd = SimpleDateFormat("MM-dd", Locale.getDefault())
    private val formatMonthDaydd = SimpleDateFormat("dd", Locale.getDefault())
    private val formatHourAndYear = SimpleDateFormat("HH:mm yyyy-MM-dd", Locale.getDefault())
    private val formatMonthDayHourMin = SimpleDateFormat("MM-dd HH:mm", Locale.getDefault())
    val formatMonthDayHour = SimpleDateFormat("MM-dd HH:mm", Locale.getDefault())
    val formatHourMinSecond = SimpleDateFormat("HH时mm分ss秒", Locale.getDefault())


    /**
     * 获取当前时间戳
     *
     * @return 系统时间
     */
    fun getTimeDate(): String? {
        return Date().time.toString()
    }

    /**
     * 获取当前时间戳
     *
     * @return 系统时间
     */
    fun getTimeDateLong(): Long {
        return Date().time
    }

    /**
     * 获取今天的日期，格式为 2019-01-10
     */
    fun getToday(): String {
        return TimeUtils.getYearMonthDay(System.currentTimeMillis())
    }

    fun getToday2(): String {
        return TimeUtils.getYearMonthDayHourMin(System.currentTimeMillis())
    }


    /**
     * 获取小时和分钟，格式为23:02
     */
    fun getHourMinute(time: Long): String {
        return formatHourMinute.format(getDate(time))
    }

    /**
     * 获取小时和分钟、秒,格式为02:23:22
     */
    fun getHourMinuteSecond(time: Long): String {
        return formatHourMinuteSecond.format(getDate(time))
    }

    /**
     * 获取月日的字符串，格式为 10月10日
     */
    fun getMonthDay(time: Long): String {
        return formatMonthDay.format(getDate(time))
    }

    fun getMonthDay_(time: Long): String {
        return formatMonthDay_.format(getDate(time))
    }

    fun getMonthDayMMdd(time: Long): String {
        return formatMonthDayMMdd.format(getDate(time))
    }

    fun geMonthDaydd(time: Long): String {
        return formatMonthDaydd.format(getDate(time))
    }

    fun getMonthDayHourMin(time: Long): String {
        return formatMonthDayHourMin.format(getDate(time))
    }

    fun getHourMinSecond(time: Long): String {
        return formatHourMinSecond.format(getDate(time))
    }

    fun getDate(time: Long, format: SimpleDateFormat): String {
        return format.format(getDate(time))
    }

    /**
     * 获取年月日的字符串，格式为 2019-01-10
     */
    fun getYearMonthDay(time: Long): String {
        return formatYearMonthDay.format(getDate(time))
    }

    fun getYearMonthDaySeries(time: Long?): String {
        return formatYearMonthDaySeries.format(getDate(time))
    }

    fun getDateSeries(date: String): Date? {
        return formatYearMonthDaySeries.parse(date)
    }

    fun getMonthDayHourMinute(time: Long): String {
        return formatMonthDayHourMinute.format(getDate(time))
    }

    /***
     * 格式为 20/4 03:23
     */
    fun getMonthDayHourMinuteDetail(time: Long): String {
        return formatMonthDayHourMinuteDetail.format(getDate(time))
    }


    /**
     * 获取年月日的字符串，格式为 2019/01/10 12:10:00
     */
    fun getYearMonthDayHourMin(time: Long): String {
        return formatYearMonthDay2.format(getDate(time))
    }

    /**
     * 获取年月日的字符串，格式为 2019.01.10 12:10
     */
    fun getYearMonthDayHour2(time: Long): String {
        return formatYearMonthDay4.format(getDate(time))
    }

    /**
     * 获取年月日的字符串，格式为 2019-01-10
     */
    fun getYearMonthDayHour(time: Long): String {
        return formatYearMonthDayHour.format(getDate(time))
    }

    /**
     * 获取年月日的字符串，格式为 yyyy年MM月dd日
     */
    fun getYearMonthDayHour3(time: Long): String {
        return formatYearMonthDay5.format(getDate(time))
    }

    /**
     * 获取年月日的字符串，格式为 2019-01-10 10:25
     */
    fun getYearMonthDayHourMinute(time: Long): String {
        return formatYearMonthDayHourMin.format(getDate(time))
    }


    /**
     * 获取年月日的字符串，格式为 2019-01-10 10:25
     */
    fun getYearMonthDayHourMinuteSecond(time: Long): String {
        return formatYearMonthDayHourMinSecond.format(getDate(time))
    }

    /**
     * 获取年月日的字符串，格式为 2019-01
     */
    fun getYearMonth(time: Long): String {
        return formatYearMonth.format(getDate(time))
    }

    fun getYearMonth2(time: Long): String {
        return formatYearMonth2.format(getDate(time))
    }

    fun getMonth(time: Long): String {
        return formatMonth.format(getDate(time))
    }

    fun getDay(time: Long): String {
        return formatMonthDaydd.format(getDate(time))
    }

    fun getYear(time: Long): String {
        return formatYear.format(getDate(time))
    }

    /**
     * 获取年月日的字符串，格式为 2019/01/10
     */
    fun getYearMonthDay_(time: Long): String {
        return formatYearMonthDay_.format(getDate(time))
    }

    fun getYearMonthDay3(time: Long): String {
        return formatYearMonthDay3.format(getDate(time))
    }

    fun getYearMonthDay4(time: Long): String {
        return formatMonthDayDefault.format(getDate(time))
    }

    /**
     * 生成正式中文星期格式，格式为：周一
     */
    fun getDayOfWeek2(time: Long): String {
        return when (getDayOfWeek1(time)) {
            1 -> "周一"
            2 -> "周二"
            3 -> "周三"
            4 -> "周四"
            5 -> "周五"
            6 -> "周六"
            else -> "周日"
        }
    }

    /**
     * 生成正式中文星期格式，格式为：一
     */
    fun getDayOfWeek3(time: Long): String {
        return when (getDayOfWeek1(time)) {
            1 -> "一"
            2 -> "二"
            3 -> "三"
            4 -> "四"
            5 -> "五"
            6 -> "六"
            else -> "日"
        }
    }

    fun getDayOfWeek(time: Long): String {
        return when (getDayOfWeek1(time)) {
            1 -> "星期一"
            2 -> "星期二"
            3 -> "星期三"
            4 -> "星期四"
            5 -> "星期五"
            6 -> "星期六"
            else -> "星期日"
        }
    }

    fun getDayOfWeekWithEn(time: Long): String {
        return when (getDayOfWeek1(time)) {
            1 -> "Mon"
            2 -> "Tue"
            3 -> "Wen"
            4 -> "Thu"
            5 -> "Fri"
            6 -> "Sat"
            else -> "Sun"
        }
    }

    fun getMonthOfZH(time: Int): String {
        return when (time) {
            1 -> "一月份"
            2 -> "二月份"
            3 -> "三月份"
            4 -> "四月份"
            5 -> "五月份"
            6 -> "六月份"
            7 -> "七月份"
            8 -> "八月份"
            9 -> "九月份"
            10 -> "十月份"
            11 -> "十一月份"
            12 -> "十二月份"
            else -> ""
        }
    }

    /**
     * 获取星期几，格式为：1 - 7
     */
    fun getDayOfWeek1(time: Long): Int {
        val calendar = getCalendar(getDate(time))
        var result = calendar.get(Calendar.DAY_OF_WEEK)
        // 返回的星期数是按照周日为第一天的，所以需要转换成周一为第一天
        if (result == 1) {
            result = 7
        } else {
            result--
        }
        return result
    }


    /**
     * 判断时间是否为今天
     */
    fun isToday(time: Long): Boolean {
        return isSameDay(time, System.currentTimeMillis())
    }

    /**
     * 判断时间是否为昨天
     */
    fun isYesterday(time: Long): Boolean {
        var timeTemp = time
        SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        getYearMonthDay(time)
        //将当前判断时间加上一天，如果和今天处于同一天，则表示为昨天的时间
        timeTemp += TimeUnit.DAYS.toMillis(1)
        return isToday(timeTemp)
    }

    /**
     * 判断时间是否为今天之前
     */
    fun isTodayBefore(time: Long): Boolean {
        val dateStr = SimpleDateFormat("yyyyMMdd", Locale.getDefault()).format(getDate(time))//保存的时间
        val getTodayStr = SimpleDateFormat(
            "yyyyMMdd",
            Locale.getDefault()
        ).format(getDate(System.currentTimeMillis()))//当前的时间
        return toInt(dateStr) < toInt(getTodayStr)
    }

    /**
     * 判断时间是否为7天之前
     */
    fun isTodayBefore7(time: Long): Boolean {
        val dateStr = SimpleDateFormat("yyyyMMdd", Locale.getDefault()).format(getDate(time))//保存的时间
        val getTodayStr = SimpleDateFormat(
            "yyyyMMdd",
            Locale.getDefault()
        ).format(getDate(System.currentTimeMillis()))//当前的时间
        return toInt(dateStr) + 6 < toInt(getTodayStr)
    }

    /**
     * 是否是明天
     */
    fun isTomorrow(time: Long): Boolean {
        var timeTemp = time
        timeTemp -= TimeUnit.DAYS.toMillis(1)
        return isToday(timeTemp)
    }


    /**
     * 判断时间是否为前天
     */
    fun isTheDayBeforeYesterday(time: Long): Boolean {
        var timeTemp = time
        timeTemp += TimeUnit.DAYS.toMillis(2)
        return isToday(timeTemp)
    }

    /**
     * 判断时间是否在本月
     */
    fun isCurrentMonth(time: Long): Boolean {
        return isSameYearAndMonth(time, System.currentTimeMillis())
    }

    /**
     * 判断时间是否在本年
     */
    fun isCurrentYear(time: Long): Boolean {
        return isSameYear(time, System.currentTimeMillis())
    }


    fun isSameDay(time1: Long, time2: Long): Boolean {
        return isSameDay(Date(time1), Date(time2))
    }

    fun isSameDay(date1: Date, date2: Date): Boolean {
        return (getYear(date1) == getYear(date2)
                && getMonth(date1) == getMonth(date2)
                && getDay(date1) == getDay(date2))
    }

    fun isSameWeek(time1: Long, time2: Long): Boolean {
        return getWeekOfYear(Date(time1)) == getWeekOfYear(Date(time2))
    }

    fun isSameYearAndMonth(time1: Long, time2: Long): Boolean {
        val sameYear = isSameYear(time1, time2)
        val sameMonth = isSameMonth(time1, time2)
        return sameYear && sameMonth
    }

    fun isSameMonth(time1: Long, time2: Long): Boolean {
        return getMonth(Date(time1)) == getMonth(Date(time2))
    }

    fun isSameYear(time1: Long, time2: Long): Boolean {
        return getYear(Date(time1)) == getYear(Date(time2))
    }


    /**
     * 获取第一次安装app的时间
     */
    fun getFirstInstallTime(): Long {
        return AppUtils.getPackageInfo().firstInstallTime
    }


    /**
     * 获取安装app的天数
     */
    fun getInstalledDays(): Int {
        val installTime = getFirstInstallTime()
        val subTime = System.currentTimeMillis() - installTime
        val dayTime = 24 * 60 * 60 * 1000
        var dayNum = (subTime / dayTime).toInt()
        dayNum = if (subTime % dayTime == 0L) dayNum else dayNum + 1
        return dayNum
    }


    /**
     * 获取安装app的分钟数
     */
    fun getInstalledMinutes(): Int {
        val installTime = getFirstInstallTime()
        val subTime = System.currentTimeMillis() - installTime
        val dayTime = 60 * 1000
        var dayNum = (subTime / dayTime).toInt()
        dayNum = if (subTime % dayTime == 0L) dayNum else dayNum + 1
        return dayNum
    }


    /**
     * 获取安装app的小时数
     */
    fun getInstalledHours(): Int {
        val installTime = getFirstInstallTime()
        val subTime = System.currentTimeMillis() - installTime
        val dayTime = 60 * 60 * 1000
        var dayNum = (subTime / dayTime).toInt()
        dayNum = if (subTime % dayTime == 0L) dayNum else dayNum + 1
        return dayNum
    }

    /**
     * 获取毫秒级单位
     * @param time 秒级单位或者毫秒单位
     */
    fun getTimeByMillisecond(time: Long): Long {
        val millis = Calendar.getInstance().timeInMillis
        return if (!TextUtils.isEmpty(millis.toString())) {
            if (millis.toString().length == time.toString().length) {  // 毫秒级单位
                time
            } else {
                time * 1000
            }
        } else {
            time
        }
    }

    /**
     * 获取秒级单位
     * @param time 秒级单位或者毫秒单位
     */
    fun getTimeBySecond(time: Long): Long {
        val millis = Calendar.getInstance().timeInMillis
        return if (!TextUtils.isEmpty(millis.toString())) {
            if (millis.toString().length == time.toString().length) {  // 毫秒级单位
                time / 1000
            } else {
                time
            }
        } else {
            time
        }
    }


    private fun getCalendar(date: Date): Calendar {
        val calendar = Calendar.getInstance()
        calendar.time = date
        return calendar
    }

    private fun getDate(time: Long?): Date {
        return Date(time ?: System.currentTimeMillis())
    }

    /**
     * 获取年份
     */
    private fun getYear(date: Date): Int {
        val calendar = getCalendar(date)
        return calendar.get(Calendar.YEAR)
    }

    /**
     * 获取月份
     */
    fun getMonth(date: Date): Int {
        val calendar = getCalendar(date)
        // Calendar的月份是从0开始的
        return calendar.get(Calendar.MONTH) + 1
    }

    /**
     * 获取日
     */
    private fun getDay(date: Date): Int {
        val calendar = getCalendar(date)
        return calendar.get(Calendar.DAY_OF_MONTH)
    }


    /**
     * 获取小时
     */
    private fun getHour(date: Date): Int {
        return getCalendar(date).get(Calendar.HOUR) + 1
    }

    /**
     * 获取分钟
     */
    private fun getMinute(date: Date): Int {
        return getCalendar(date).get(Calendar.MINUTE)
    }

    /**
     * 获取周数，既当前是一年中的第几周
     */
    private fun getWeekOfYear(date: Date): Int {
        val calendar = getCalendar(date)
        return calendar.get(Calendar.WEEK_OF_YEAR)
    }

    /**
     * 根据两个相对的时间戳返回时间格式 78’88”
     * @param time 毫秒值
     */
    fun getMinuteSecond(time: Long): String {
        val seconds = time / 1000
        val minutesStr: String =
            if ((seconds / 60).toString().length == 1) "${seconds / 60}" else "${seconds / 60}"
//        val secondsStr = if ((seconds % 60).toString().length == 1) "0${seconds % 60}" else "${seconds % 60}"
//        return "${minutesStr}’${secondsStr}”"
        return "$minutesStr'"
    }

    /**
     * 根据两个相对的时间戳返回时间格式 78’88”
     * @param time 秒值
     */
    fun getMinuteSecond2(time: Long): String {
        val seconds = getTimeBySecond(time)
        val minutesStr: String =
            if ((seconds / 60).toString().length == 1) "0${seconds / 60}" else "${seconds / 60}"
        val secondsStr =
            if ((seconds % 60).toString().length == 1) "0${seconds % 60}" else "${seconds % 60}"
        return "${minutesStr}’${secondsStr}”"
    }

    /**
     * 根据两个相对的时间戳返回时间格式 78’88”
     * @param time 秒值
     */
    fun getMinuteSecond3(time: Long): String {
        val seconds = getTimeBySecond(time)
        val minutesStr: String =
            if ((seconds / 60).toString().length == 1) "0${seconds / 60}" else "${seconds / 60}"
        val secondsStr =
            if ((seconds % 60).toString().length == 1) "0${seconds % 60}" else "${seconds % 60}"
        return "${minutesStr}:${secondsStr}"
    }

    /**
     * 获取年月日的下一天
     * @param day 1，2，3往后的天数，-1-2-3往前的天数
     */
    fun getYearMonthNextDay(time: Long, day: Int): String {
        val calendar = getCalendar(Date(time))
        calendar.add(Calendar.DAY_OF_MONTH, day)
        return formatYearMonthDay.format(calendar.time)
    }

    fun getYearMonthNextDay(time: Date, day: Int): Date? {
        val str = getYearMonthNextDay(time.time, day)
        return getDate(str)
    }

    fun getYearMonthNextDayDate(time: Date, day: Int): Date {
        val calendar = getCalendar(time)
        calendar.add(Calendar.DAY_OF_MONTH, day)
        return calendar.time
    }

    fun getYearMonthNextMonthDate(time: Date, day: Int): Date {
        val calendar = getCalendar(time)
        calendar.add(Calendar.MONTH, day)
        return calendar.time
    }

    /**
     * 年月日格式的时间转换成毫秒值，格式：2018-12-12
     */
    fun u(date: String): Long {
        return formatYearMonthDay.parse(date).time
    }

    fun getMillisecondByDateHour(date: String): Long {
        return formatYearMonthDayHour.parse(date).time
    }

    fun getSecondByDate(date: String): Long {
        return formatYearMonthDayHourMinSecond.parse(date).time
    }

    fun getDate(date: String): Date? {
        return formatYearMonthDay.parse(date)
    }

    fun getDateMonth(date: String): Date? {
        return formatYearMonthDayHourMin.parse(date)
    }

    /**
     * 是否是N天前
     */
    fun isInNDayBefore(time: Long, n: Long = 1): Boolean {
        var timeTemp = time
        timeTemp += TimeUnit.DAYS.toMillis(n)
        return isBeforeDay(timeTemp)
    }

    /**
     * 是否是N天后
     */
    fun isInNDayLater(time: Long, n: Long = 1): Boolean {
        var timeTemp = time
        timeTemp -= TimeUnit.DAYS.toMillis(n)
        return isLaterDay(timeTemp)
    }

    fun isBeforeDay(time: Long): Boolean {
        val nowDate = getDate(getDate(Date(System.currentTimeMillis())))
        return Date(time).before(nowDate)
    }

    fun isLaterDay(time: Long): Boolean {
        val nowDate = getDate(getDate(Date(System.currentTimeMillis())))
        return nowDate?.before(Date(time)) ?: false
    }

    fun getDataByHour(date: String): Date {
        return formatHourMinute.parse(date)
    }

    fun getDataByHour(date: Date): String {
        return getHourMinute(date.time)
    }

    fun getDate(date: Date?): String {
        return getYearMonthDay(date?.time ?: 0)
    }

    fun getTodayData(): String {
        return getDate(Date())
    }

    /**
     * 返回小时和年份时间，格式：12:10  2019-03-01
     */
    fun getHourAndYear(time: Long): String {
        return formatHourAndYear.format(getDate(time))
    }

    /**
     * 返回根据自定义simpleDateFormat 转换的日历
     */
    fun getDateFormat(time: Long, dateFormat: SimpleDateFormat): String {
        return dateFormat.format(getDate(time))
    }

    /**
     *将秒转化成小时分钟秒
     */
    fun formatMiss(miss: Int): String {
        val hh = if (miss / 3600 > 9) (miss / 3600).toString() else "0" + miss / 3600
        val mm =
            if (miss % 3600 / 60 > 9) (miss % 3600 / 60).toString() else "0" + miss % 3600 / 60
        val ss =
            if (miss % 3600 % 60 > 9) (miss % 3600 % 60).toString() else "0" + miss % 3600 % 60
        return "$hh:$mm:$ss"
    }

    fun formatMiss2(m: Int): String {
        val miss = abs(m)
        val mm =
            if (miss % 3600 / 60 > 9) (miss % 3600 / 60).toString() else "0" + miss % 3600 / 60
        val ss =
            if (miss % 3600 % 60 > 9) (miss % 3600 % 60).toString() else "0" + miss % 3600 % 60
        return "$mm:$ss"
    }


    /**
     * 获取两个日期相差多少天
     */
    fun getDateBy2Day(startDate: Date, endDate: Date): Long {
        return getDateBy2Day(getDate(startDate), getDate(endDate))
    }

    /**
     * 获取两个日期相差多少天
     */
    fun getDateBy2Day(startStr: String, endStr: String): Long {
        val startDate = formatYearMonthDay.parse(startStr)
        val endDate = formatYearMonthDay.parse(endStr)
        return (endDate.time - startDate.time) / (60 * 60 * 24 * 1000)
    }

    /**
     * 获取两个日期相差多少秒
     */
    fun getDateBy2Second(startDate: Date, endDate: Date): Long {
        return (endDate.time - startDate.time) / 1000
    }

    /**
     * 获取时间（10位数的时间戳）
     */
    fun timeStamp2Date(seconds: String?, format: String?): String {
        var format = format
        if (seconds == null || seconds.isEmpty() || seconds == "null") {
            return ""
        }
        if (format == null || format.isEmpty()) format = "yyyy-MM-dd HH:mm:ss"
        val sdf = SimpleDateFormat(format)
        return sdf.format(Date(java.lang.Long.valueOf(seconds + "000")))
    }

    /**
     * 判断当前月有多少天
     */
    fun getMonthOfDay(year: Int, month: Int): Int {
        var day = 0
        if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
            day = 29
        } else {
            day = 28
        }
        when (month) {
            1, 3, 5, 7, 8, 10, 12 -> return 31
            4, 6, 9, 11 -> return 30
            2 -> return day
        }

        return 0
    }

    /**
     * 计算专家方案发布时间
     */
    fun calculateExpertTime(time: Long): String {
        val nowTime = System.currentTimeMillis() // 获取当前时间的毫秒数
        val msg: String
        val dateDiff = nowTime - time
        if (dateDiff > 0) {
            val dateTemp1 = dateDiff / 1000 // 秒
            val dateTemp2 = dateTemp1 / 60 // 分钟
            val dateTemp3 = dateTemp2 / 60 // 小时
            msg = when {
                dateTemp3 in 1..12 -> {
                    dateTemp3.toString() + "小时前发布"
                }
                dateTemp2 in 31..59 -> {
                    "半小时前发布"
                }
                dateTemp1 in 0..30 -> {
                    "刚刚发布"
                }
                else -> getYearMonthDayHourMinute(time) + "发布"
            }
        } else {
            msg = getYearMonthDayHourMinute(time) + "发布"
        }
        return msg
    }

    fun diffTime(diff: Long): String {
        val d = "0:0:0:0"
        val sb = StringBuilder()

        try {
            val days = diff / (1000 * 60 * 60 * 24)
            val hours = (diff - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
            val minutes =
                (diff - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60)) / (1000 * 60)
            val second =
                (diff - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60) - minutes * (1000 * 60)) / 1000
            if (days > 0L) {
                sb.append("${days}天 ")
            }
            if (hours > 0L) {
                sb.append("${hours}:")
            }
            if (minutes > 0L) {
                sb.append("${minutes}:")
            }
            sb.append(second)

            return sb.toString()
        } catch (e: Exception) {
        }
        return d
    }


    /*
     * 毫秒转化时分秒毫秒（格式）
     */
    fun formatTime2(ms: Long): String {
        var milliseconds = ms
        val seconds = (milliseconds / 1000).toInt()
        var minutes = seconds / 60
        var hours = minutes / 60
        var days = hours / 24
        var months = days / 30
        val years = months / 12

        milliseconds %= 1000
        minutes %= 60
        val secondsFinal = seconds % 60
        hours %= 24
        days %= 30
        months %= 12

        val sb = StringBuffer()
        var result = ""
        if (years > 0) {
//            result += "${years}年前"
            sb.append("${years}年")
            return sb.toString()
        }
        if (months > 0) {
//            result += "${months}个月前"
            sb.append("${months}个月")
            return sb.toString()
        }
        if (days > 0) {
//            result += "${days}天前"
            sb.append("${days}天")
            return sb.toString()
        }
        if (hours > 0) {
//            result += "${hours}小时前"
            sb.append("${hours}小时")
            return sb.toString()
        }
        if (minutes > 0) {
//            result += "${minutes}分钟前"
            sb.append("${minutes}分钟")
            return sb.toString()
        }

        if (secondsFinal > 0) {
            sb.append("${secondsFinal}秒")
            return sb.toString()
        }

        if (milliseconds > 0) {
            sb.append("${milliseconds}毫秒")
            return sb.toString()
        }
//        result += "$secondsFinal.${String.format("%03d", milliseconds)}秒"
        return result
    }

    /**
     * 将毫秒时间差转换为HH:mm:ss格式
     * @param ms 毫秒时间差值
     * @return 格式化后的时间字符串，格式为"HH:mm:ss"
     */
    fun formatTime3(ms: Long): String {
        val totalSeconds = ms / 1000
        val hours = totalSeconds / 3600
        val minutes = (totalSeconds % 3600) / 60
        val seconds = totalSeconds % 60

        return String.format("%02d:%02d:%02d", hours, minutes, seconds)
    }

    /*
     * 毫秒转化时分秒毫秒（格式）
     */
    fun formatTime(
        ms: Long, showDay: Boolean = true, showHour: Boolean = false, showMin: Boolean = false,
        showSec: Boolean = false, showMil: Boolean = false
    ): String? {
        var milliseconds = ms
        val seconds = (milliseconds / 1000).toInt()
        var minutes = seconds / 60
        var hours = minutes / 60
        var days = hours / 24
        var months = days / 30
        val years = months / 12

        milliseconds %= 1000
        minutes %= 60
        val secondsFinal = seconds % 60
        hours %= 24
        days %= 30
        months %= 12
        val sb = StringBuffer()
        if (showDay) {
            if (days > 0) {
                sb.append(days.toString() + "天")
            }
        }
        if (showHour) {
            if (hours > 0) {
                sb.append(hours.toString() + "小时")
            }
        }
        if (showMin) {
            if (minutes > 0) {
                sb.append(minutes.toString() + "分钟")
            }
        }
        if (showSec) {
            if (secondsFinal > 0) {
                sb.append(secondsFinal.toString() + "秒")
            }
        }
        if (showMil) {
            if (milliseconds > 0) {
                sb.append(milliseconds.toString() + "毫秒")
            }
        }
        return if(sb.toString().isNullOrEmpty()) "0${getString(R.string.common_minutes_hint)}" else sb.toString()
    }

    /*
     * 毫秒转化时分秒毫秒（格式）
     */
    fun formatTimeToList(ms: Long): List<Int> {
        val mList = mutableListOf<Int>()
        var milliseconds = ms
        val seconds = (milliseconds / 1000).toInt()
        var minutes = seconds / 60
        val hours = minutes / 60
        val days = hours / 24

        milliseconds %= 1000
        minutes %= 60
        val secondsFinal = seconds % 60

        mList.add(days)
        mList.add(hours)
        mList.add(minutes)
        mList.add(secondsFinal)
        return mList
    }

    /*
 * 毫秒转化时分秒毫秒（格式）
 */
    fun formatTimeByBean(ms: Long): TimeComponents {
        var milliseconds = ms
        val seconds = (milliseconds / 1000).toInt()
        var minutes = seconds / 60
        var hours = minutes / 60
        var days = hours / 24
        var months = days / 30
        val years = months / 12

        milliseconds %= 1000
        minutes %= 60
        val secondsFinal = seconds % 60
        hours %= 24
        days %= 30
        months %= 12

        return TimeComponents(
            days = days.toLong(),
            hours = hours.toLong(),
            minutes = minutes.toLong(),
            seconds = secondsFinal.toLong(),
            milliseconds = milliseconds
        )
    }

    /**
     * 将时间类型的时间转成String类型
     *
     * @param date    时间类型的时间,如：1481275618528
     * @param outType 转出的类型String，如：dd/MM/yyyy HH:mm:ss
     * @return 返回的String类型的时间
     */
    fun transferTimeFromDate(date: Date?, outType: String?): String {
        var nowTime = ""
        nowTime = if (date != null) {
            val sim = SimpleDateFormat(outType, Locale.getDefault())
            sim.format(date)
        } else {
            return nowTime
        }
        return nowTime
    }

    /**
     * 将时间类型的时间转成String类型
     *
     * @param date    时间类型的时间,如：1481275618528
     * @param outType 转出的类型String，如：dd/MM/yyyy HH:mm:ss
     * @return 返回的String类型的时间
     */
    fun transferTimeFromDateInt(date: Date?, outType: String?): Int {
        var nowTime = 0
        if (date != null) {
            try {
                val sim = SimpleDateFormat(outType)
                nowTime = sim.format(date).toInt()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        } else {
            return nowTime
        }
        return nowTime
    }

    /**
     * 日期转字符串
     *
     * @param date
     * @return
     */
    fun formatDate(date: Date?, format: String?): String? {
        val sdf = SimpleDateFormat(format, Locale.getDefault())
        return date?.let { sdf.format(it) }
    }

    /**
     * 根据字符日期返回星期几
     *
     * @param
     * @return
     */
    fun getWeek(dateTime: String?): String {
        dateTime.isNullOrEmpty().yes {
            return ""
        }
        var week = ""
        val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        try {
            val date = dateTime?.let { sdf.parse(it) }
            val dateFm = SimpleDateFormat("EEEE", Locale.getDefault())
            week = date?.let { dateFm.format(it) }.toString()
            week = week.replace("星期".toRegex(), "周")
        } catch (e: ParseException) {
            e.printStackTrace()
        }
        return week
    }

    /**
     * 根据字符日期返回星期几
     *
     * @param
     * @return
     */
    fun getWeek3(dateTime: String?): Int {
        dateTime.isNullOrEmpty().yes {
            return 0
        }
        var weekIng = 0
        val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        try {
            val date = sdf.parse(dateTime)
            val dateFm = SimpleDateFormat("EEEE", Locale.getDefault())
            var week = dateFm.format(date)
            week = week.replace("星期".toRegex(), "")
            when (week) {
                "日" -> weekIng = 0
                "一" -> weekIng = 1
                "二" -> weekIng = 2
                "三" -> weekIng = 3
                "四" -> weekIng = 4
                "五" -> weekIng = 5
                "六" -> weekIng = 6
                else -> {}
            }
        } catch (e: ParseException) {
            e.printStackTrace()
        }
        return weekIng
    }

    /**
     * 将long类型的时间转成String类型
     *
     * @param inTime  long类型的时间,如：1481275618528
     * @param outType 转出的类型String，如：dd/MM/yyyy HH:mm:ss
     * @return 返回的String类型的时间
     */
    fun transferTimeFromLong(inTime: Long, outType: String?): String {
        outType.isNullOrEmpty().yes {
            return ""
        }
        val sim = SimpleDateFormat(outType, Locale.getDefault())
        val date = Date(inTime)
        return sim.format(date)
    }

    /**
     * 日期转时间戳
     *
     * @param date
     * @return
     */
    fun transForMilliSecond(date: Date?): Long {
        return date?.time ?: 0
    }

    /**
     * 日期字符串转时间戳
     *
     * @param dateStr
     * @param tim     如"yyyy-mm-dd"
     * @return
     */
    fun transForMilliSecondByTim(dateStr: String?, tim: String?): Long {
        val sdf = SimpleDateFormat(tim)
        var date: Date? = null
        try {
            date = sdf.parse(dateStr)
        } catch (e: ParseException) {
            e.printStackTrace()
        }
        return if (date == null) 0 else transForMilliSecond(
            date
        )
    }

    /**
     * 时间戳转换成字符窜
     *
     * @param milSecond
     * @param pattern
     * @return
     */
    fun getDateToString(milSecond: Long, pattern: String?): String {
        pattern.isNullOrEmpty().yes {
            return ""
        }
        val date = Date(milSecond)
        val format = SimpleDateFormat(pattern, Locale.getDefault())
        return format.format(date)
    }


    /**
     * 获取该月天数
     */
    fun getCurrentMonthDay(millSec: Long): Int {
        val calendar = Calendar.getInstance()
        calendar.timeInMillis = millSec
        calendar[Calendar.DATE] = 1
        calendar.roll(Calendar.DATE, -1)
        return calendar[Calendar.DATE]
    }

    /**
     * 本年
     *
     * @param
     * @return
     */
    fun getCurYear(): Int {
        val currCal = Calendar.getInstance()
        return currCal[Calendar.YEAR]
    }


    /**
     * 本月
     *
     * @param
     * @return
     */
    fun getCurMonth(): Int {
        val currCal = Calendar.getInstance()
        return currCal[Calendar.MONTH] + 1
    }

    /**
     * 获取指定时间戳的年份和月份
     * @param timeInMillis 时间戳，单位为毫秒
     * @return Pair<Int, Int> 第一个元素是年份，第二个元素是月份（1-12）
     */
    fun getYearAndMonth(timeInMillis: Long = System.currentTimeMillis()): Pair<Int, Int> {
        val calendar = Calendar.getInstance()
        calendar.timeInMillis = timeInMillis
        val year = calendar.get(Calendar.YEAR)
        val month = calendar.get(Calendar.MONTH) + 1 // 转换为1-12
        return Pair(year, month)
    }

    /**
     * 上一个月
     *
     * @param
     * @return
     */
    fun getLastMonth(): Int {
        val calendar = Calendar.getInstance()
        calendar.add(Calendar.MONTH, -1)
        return calendar.get(Calendar.MONTH) + 1
    }
    /**
     * 上一个年月
     *
     * @param
     * @return
     */
    fun getLastYearMonth(outType: String?=null): String {
        var cerOutType: String? = "yyyy-MM"
        outType.isNullOrEmpty().no { cerOutType = outType }
        val calendar = Calendar.getInstance()
        calendar.add(Calendar.MONTH, -1)
        val date = calendar.time
        val formatter = SimpleDateFormat(cerOutType, Locale.getDefault())
        return formatter.format(date)
    }
    /**
     * @Description 获取年份
     * @param pattern 格式
     * @param num 负数为之前年,0为当前年,正数为之后年
     */
    fun getYears(pattern: String?, num: Int): String {
        pattern.isNullOrEmpty().yes {
            return "---"
        }
        val format = SimpleDateFormat(pattern, Locale.getDefault())
        val c = Calendar.getInstance()
        c.time = Date()
        c.add(Calendar.YEAR, num)
        val y = c.time
        return format.format(y)
    }

    /**
     * 获取当前时间戳
     *
     * @return 系统时间
     */
    fun getTimeStamp2(pattern: String?, mDate: Date?): String {
        pattern.isNullOrEmpty().yes {
            return ""
        }

        mDate?.let {
            return SimpleDateFormat(pattern, Locale.getDefault()).format(mDate)
        }

        return ""
    }

    // 辅助方法使用函数
    fun getDateMillis(year: Int, month: Int, day: Int): Long = Calendar.getInstance().apply {
        set(year, month - 1, day)
        set(Calendar.HOUR_OF_DAY, 0)
        set(Calendar.MINUTE, 0)
        set(Calendar.SECOND, 0)
        set(Calendar.MILLISECOND, 0)
    }.timeInMillis

    //获取传入时间戳的前N天的年月日数据
    fun getPreviousDaysFormatted(timestamp: Long, num: Int): List<String> {
        val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        val calendar = Calendar.getInstance()
        calendar.timeInMillis = timestamp
        calendar.set(Calendar.HOUR_OF_DAY, 0)
        calendar.set(Calendar.MINUTE, 0)
        calendar.set(Calendar.SECOND, 0)
        calendar.set(Calendar.MILLISECOND, 0)

        return ArrayList<String>(num).apply {
            repeat(num) {
                add(sdf.format(calendar.time))
                calendar.add(Calendar.DAY_OF_YEAR, -1)
            }
        }
    }

    fun getPreviousDayString(timestamp: Long, num: Int): String {
        require(num >= 0) { "Number of days must be non-negative" }
        require(timestamp > 0) { "Invalid timestamp" }
        val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        val calendar = Calendar.getInstance()
        calendar.timeInMillis = timestamp
        calendar.add(Calendar.DAY_OF_YEAR, -num)
        calendar.set(Calendar.HOUR_OF_DAY, 0)
        calendar.set(Calendar.MINUTE, 0)
        calendar.set(Calendar.SECOND, 0)
        calendar.set(Calendar.MILLISECOND, 0)
        return sdf.format(calendar.time)
    }

    fun getPreviousDayLong(timestamp: Long, num: Int): Long {
        require(num >= 0) { "Number of days must be non-negative" }
        require(timestamp > 0) { "Invalid timestamp" }
        val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        val calendar = Calendar.getInstance()
        calendar.timeInMillis = timestamp
        calendar.add(Calendar.DAY_OF_YEAR, -num)
        calendar.set(Calendar.HOUR_OF_DAY, 0)
        calendar.set(Calendar.MINUTE, 0)
        calendar.set(Calendar.SECOND, 0)
        calendar.set(Calendar.MILLISECOND, 0)
        return calendar.time.time
    }

    /**
     * 计算给定时间戳与当前系统时间戳相差的天数
     *
     * @param timestamp 给定的时间戳
     * @return 相差的天数：
     *         - 如果给定时间戳等于当前系统时间戳（同一天），返回0
     *         - 如果给定时间戳是当前系统时间戳的前一天，返回1
     *         - 如果给定时间戳是当前系统时间戳的前两天，返回2
     *         - 以此类推
     */
    fun getDayDifferenceFromNow(timestamp: Long): Int {
        // 获取当前系统时间戳并转换为当天的开始时间（00:00:00）
        val currentTimestamp = getTimeDateLong()
        val currentDayStart = getTodayStart(currentTimestamp)

        // 将给定的时间戳转换为其所在天的开始时间（00:00:00）
        val givenDayStart = getTodayStart(timestamp)

        // 如果给定时间戳的日期部分等于当前时间戳的日期部分，则返回0
        if (givenDayStart == currentDayStart) {
            return 0
        }

        // 计算两个时间戳（日期部分）之间相差的毫秒数
        val diffMillis = currentDayStart - givenDayStart

        // 将毫秒数转换为天数（1天 = 24小时 * 60分钟 * 60秒 * 1000毫秒）
        val diffDays = (diffMillis / (24 * 60 * 60 * 1000)).toInt()

        return diffDays
    }


    /**
     * 本地时间戳转换为时间戳
     *
     * @return 格林威治时间
     */
    fun convertLocalDateTimeToTimestamp(localDateTimeStr: String): Long {
        val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
        val date = dateFormat.parse(localDateTimeStr)
        return date?.time?:0
    }

    /**
     * 本地日期时间转换为格林威治时间
     *
     * @return 格林威治时间
     */
    fun convertLocalToGMT(date: Date): String {
        val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
        dateFormat.timeZone = TimeZone.getTimeZone("GMT")
        return dateFormat.format(date)
    }

    /**
     * 格林威治时间转换为本地日期时间
     *
     * @return 本地日期时间
     */
    fun convertGMTToLocal(gmtTime: String, localDateFormat: SimpleDateFormat): String? {
        val gmtDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
        gmtDateFormat.timeZone = TimeZone.getTimeZone("GMT")
        val date = gmtDateFormat.parse(gmtTime)
        return date?.let {localDateFormat.format(it) }
    }
    /**
     * 格林威治时间转换为本地日期时间
     *
     * @return 本地日期时间
     */
    fun convertGMTToLocal(mTime: String?, localDateFormat: SimpleDateFormat, dateTime: String): String? {
        if (mTime.isNullOrEmpty()) {
            return null
        }
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val dateTimeFormatter =  DateTimeFormatter.ofPattern(dateTime)
            // 对于 Android 8.0 (API 26) 及以上版本
            val offsetDateTime = OffsetDateTime.parse(mTime)
            offsetDateTime.format(dateTimeFormatter)
        } else {
            val parser = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault())
            val date = parser.parse(mTime)
            date?.let { localDateFormat.format(it) }
        }
    }

    fun getTimerZJ(date: String): String? {
        val inputTimeDate = formatYearMonthDayHourMinSecond.parse(date)?:Date()
        val inputTimeLong = formatYearMonthDaySeries.format(inputTimeDate).toLong()
        val todayTimeLong = formatYearMonthDaySeries.format(Date()).toLong()
        return when(todayTimeLong-inputTimeLong){
            1L->  "昨天 ${SimpleDateFormat("HH:mm", Locale.getDefault()).format(inputTimeDate)}"
            0L ->  "今天  ${SimpleDateFormat("HH:mm", Locale.getDefault()).format(inputTimeDate)}"
            else->date
        }

    }

    /**
     * 将毫秒值转换为分钟值（向下取整）
     * @param millis 毫秒值
     * @return Long 分钟值
     */
    fun convertMillisToMinutes(millis: Long): Long {
        require(millis >= 0) { "毫秒值不能为负数" }
        val millisecondsInMinute = 1000 * 60L
        return (millis / millisecondsInMinute)
    }

    /**
     * 将天数值转换为分钟值
     * @param millis 毫秒值
     * @return Long 分钟值
     */
    fun convertDaysToMinutes(days: Int): Long {
        require(days >= 0) { "天数不能为负数" }
        return days * 1440L
    }

    /**
     * 获取指定时间戳的月份日号
     * @param timestamp 时间戳
     * @return Int 月份值
     */
    fun getDayOfMonthLegacy(timestamp: Long, timeZone: TimeZone = TimeZone.getDefault()): Int {
        val calendar = Calendar.getInstance(timeZone).apply {
            timeInMillis = timestamp
        }
        return calendar[Calendar.DAY_OF_MONTH]
    }

    /**
    * 解析日期字符串获取当日时间戳区间
    * @param dateStr 格式必须为"yyyy-MM-dd" (如"2025-03-26")
    * @param zone 时区ID，默认为系统时区
    * @return Pair<开始时间戳, 结束时间戳>
    */
    fun getDayTimestampRangeLegacy(dateStr: String, pattern: String = "yyyy-MM-dd", timeZone: TimeZone = TimeZone.getDefault()): Pair<Long, Long>? {
        return try {
            val sdf = SimpleDateFormat(pattern, Locale.US).apply {
                this.timeZone = timeZone
                isLenient = false // 严格模式检测无效日期
            }

            // 解析日期到Calendar
            val calendar = Calendar.getInstance(timeZone).apply {
                time = sdf.parse(dateStr)!!
                set(Calendar.HOUR_OF_DAY, 0)
                set(Calendar.MINUTE, 0)
                set(Calendar.SECOND, 0)
                set(Calendar.MILLISECOND, 0)
            }

            val start = calendar.timeInMillis

            // 结束时间=次日零点减1毫秒
            calendar.add(Calendar.DAY_OF_MONTH, 1)
            val end = calendar.timeInMillis - 1

            start to end
        } catch (e: Exception) {
            null
        }
    }
    /**
     * 解析时间戳获取当日时间戳区间
     * @param timestamp 时间戳
     * @param zone 时区ID，默认为系统时区
     * @return Pair<开始时间戳, 结束时间戳>
     */
    fun getDayRangeLegacy(timestamp: Long, timeZone: TimeZone = TimeZone.getDefault()): Pair<Long, Long> {
        val calendar = Calendar.getInstance(timeZone).apply {
            timeInMillis = timestamp
            set(Calendar.HOUR_OF_DAY, 0)
            set(Calendar.MINUTE, 0)
            set(Calendar.SECOND, 0)
            set(Calendar.MILLISECOND, 0)
        }
        val start = calendar.timeInMillis
        calendar.add(Calendar.DAY_OF_MONTH, 1)
        val end = calendar.timeInMillis - 1
        return start to end
    }

    /**
     * 获取当前月份第一天时间戳的实现方法
     * @param timeZone 目标时区，默认系统时区
     */
    fun getFirstDayOfMonthLegacy(timeZone: TimeZone = TimeZone.getDefault()): Long {
        val calendar = Calendar.getInstance(timeZone)
        calendar.set(Calendar.DAY_OF_MONTH, 1)
        return calendar.timeInMillis
    }

    /**
     * 获取当前月份最后一天时间戳的实现方法
     * @param timeZone 目标时区，默认系统时区
     */
    fun getLastDayLegacy(timeZone: TimeZone = TimeZone.getDefault()): Long {
        val calendar =  Calendar.getInstance(timeZone)
        val lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH)
        calendar.set(Calendar.DAY_OF_MONTH, lastDay)
        return calendar.timeInMillis
    }

    /**
     * 获取指定时间戳前一天或后一天的时间戳
     * @param timestamp 输入的时间戳（毫秒）
     * @param isNextDay 是否获取后一天，true=后一天，false=前一天（默认）
     * @return 返回前一天或后一天00:00:00的时间戳
     */
    fun getPreviousDayTimestamp(timestamp: Long, isNextDay: Boolean = false): Long {
        val calendar = Calendar.getInstance()
        calendar.timeInMillis = timestamp

        // 根据isNextDay参数决定加一天还是减一天
        if (isNextDay) {
            calendar.add(Calendar.DAY_OF_MONTH, 1)  // 后一天
        } else {
            calendar.add(Calendar.DAY_OF_MONTH, -1) // 前一天
        }

        // 设置为当天的00:00:00
        calendar.set(Calendar.HOUR_OF_DAY, 0)
        calendar.set(Calendar.MINUTE, 0)
        calendar.set(Calendar.SECOND, 0)
        calendar.set(Calendar.MILLISECOND, 0)

        return calendar.timeInMillis
    }

    /**
     * 获取指定时间戳的前一天晚上8点和当天早上11点的时间戳
     * @param timestamp 指定的时间戳
     * @return Pair<前一天晚上8点的时间戳, 当天早上11点的时间戳>
     */
    /**
     * 获取指定时间戳的前一天晚上8点和当天早上11点的时间戳
     * @param timestamp 指定的时间戳
     * @param mDay 往前推的天数，1表示前一天
     * @return Pair<前mDay天晚上8点的时间戳, 前(mDay-1)天早上11点的时间戳>
     */
    fun getTimeRangeForSleep(timestamp: Long, mDay: Int = 1): Pair<Long, Long> {
        // 获取前mDay天晚上8点的时间戳
        val yesterdayNightCalendar = Calendar.getInstance().apply {
            timeInMillis = timestamp
            add(Calendar.DAY_OF_MONTH, -mDay) // 前mDay天
            set(Calendar.HOUR_OF_DAY, 20) // 晚上8点
            set(Calendar.MINUTE, 0)
            set(Calendar.SECOND, 0)
            set(Calendar.MILLISECOND, 0)
        }

        // 获取前(mDay-1)天早上11点的时间戳
        val todayMorningCalendar = Calendar.getInstance().apply {
            timeInMillis = timestamp
            add(Calendar.DAY_OF_MONTH, -(mDay - 1)) // 前(mDay-1)天
            set(Calendar.HOUR_OF_DAY, 11) // 早上11点
            set(Calendar.MINUTE, 0)
            set(Calendar.SECOND, 0)
            set(Calendar.MILLISECOND, 0)
        }

        return Pair(yesterdayNightCalendar.timeInMillis, todayMorningCalendar.timeInMillis)
    }

    /**
     * 根据时间戳获取该时间戳当天及向前推算天数的0点0分0秒时间戳数组
     * @param timestamp 输入的时间戳（毫秒）
     * @param mDay 向前推算的天数（不包含当天），如果为0则只返回当天的0点时间戳
     * @return 返回时间戳数组，第一个元素是当天的0点0分0秒时间戳，后续元素是向前推算每天的0点0分0秒时间戳
     */
    fun getDayStartTimestamps(timestamp: Long, mDay: Int): Array<Long> {
        val calendar = Calendar.getInstance()
        calendar.timeInMillis = timestamp

        // 设置为当天的0点0分0秒
        calendar.set(Calendar.HOUR_OF_DAY, 0)
        calendar.set(Calendar.MINUTE, 0)
        calendar.set(Calendar.SECOND, 0)
        calendar.set(Calendar.MILLISECOND, 0)

        val result = mutableListOf<Long>()

        // 添加当天的0点时间戳
        result.add(calendar.timeInMillis)

        // 向前推算mDay天，每天的0点0分0秒时间戳
        for (i in 1..mDay) {
            calendar.add(Calendar.DAY_OF_MONTH, -1)
            result.add(calendar.timeInMillis)
        }

        return result.toTypedArray()
    }

    /**
     * 获取当前时间的起点（00:00:00）
     *
     * @param currentTime
     * @return
     */
    fun getTodayStart(currentTime: Long): Long {
        val calendar = Calendar.getInstance()
        calendar.time = Date(currentTime)
        calendar[Calendar.HOUR_OF_DAY] = 0
        calendar[Calendar.MINUTE] = 0
        calendar[Calendar.SECOND] = 0
        calendar[Calendar.MILLISECOND] = 0
        return calendar.timeInMillis
    }

    /**
     * 去除时间戳的毫秒部分
     * @param timestamp 毫秒级时间戳
     * @return 去除毫秒部分的时间戳（最后三位变为000）
     */
    fun removeMilliseconds(timestamp: Long): Long {
        return timestamp - (timestamp % 1000)
    }

    /**
     * 根据时间戳和偏移值获取年份列表
     * @param timestamp 时间戳（毫秒）
     * @param offset 偏移值，表示要获取多少年的数据
     * @return 年份字符串列表，从当前年份开始往前推
     */
    fun getYearListByTimestampAndOffset(timestamp: Long, offset: Int): List<String> {
        val calendar = Calendar.getInstance()
        calendar.timeInMillis = timestamp
        val currentYear = calendar.get(Calendar.YEAR)

        val yearList = mutableListOf<String>()
        for (i in 0 until offset) {
            yearList.add((currentYear - i).toString())
        }

        return yearList
    }

    /**
     * 根据年月字符串获取该月份的所有天数数组
     * @param yearMonth 年月字符串，格式如"2025-5"或"2025-05"
     * @return 该月份所有天数的字符串数组，如["1", "2", "3", ..., "30"]
     */
    fun getDaysInMonth(yearMonth: String): List<String> {
        try {
            val parts = yearMonth.split("-")
            if (parts.size != 2) {
                throw IllegalArgumentException("年月格式错误，应为 yyyy-M 或 yyyy-MM")
            }

            val year = parts[0].toInt()
            val month = parts[1].toInt()

            if (month < 1 || month > 12) {
                throw IllegalArgumentException("月份必须在1-12之间")
            }

            val calendar = Calendar.getInstance()
            calendar.set(Calendar.YEAR, year)
            calendar.set(Calendar.MONTH, month - 1) // Calendar的月份从0开始
            calendar.set(Calendar.DAY_OF_MONTH, 1)

            // 获取该月的最大天数
            val maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH)

            val daysList = mutableListOf<String>()
            for (day in 1..maxDay) {
                daysList.add(day.toString())
            }

            return daysList
        } catch (e: Exception) {
            // 如果解析失败，返回空列表
            return emptyList()
        }
    }

    /**
     * 将时间戳从一个时区转换到另一个时区
     *
     * @param timestamp 需要转换的时间戳（毫秒）
     * @param sourceTimeZoneId 源时区ID，例如 "GMT+8" 或 "Asia/Shanghai"
     * @param targetTimeZoneId 目标时区ID，例如 "GMT-5" 或 "America/New_York"
     * @return 转换后的时间戳（毫秒）
     */
    fun convertTimestampBetweenTimeZones(timestamp: Long, sourceTimeZoneId: String, targetTimeZoneId: String): Long {
        val sourceTimeZone = TimeZone.getTimeZone(sourceTimeZoneId)
        val targetTimeZone = TimeZone.getTimeZone(targetTimeZoneId)

        // 获取源时区和目标时区的偏移量（相对于UTC）
        val sourceOffset = sourceTimeZone.getOffset(timestamp)
        val targetOffset = targetTimeZone.getOffset(timestamp)

        // 计算时区差异并应用到时间戳
        return timestamp + (targetOffset - sourceOffset)
    }

    /**
     * 获取当前设备的时区ID
     * @return 时区ID，例如 "Asia/Shanghai"
     */
    fun getTimeZone(): String {
        return TimeZone.getDefault().id
    }

    /**
     * 获取当前设备的UTC偏移量（小时）
     * 例如：东八区返回8，西五区返回-5
     * @return UTC偏移量（小时）
     */
    fun getCurrentUtcOffset(): Int {
        val timeZone = TimeZone.getDefault()
        val offsetMillis = timeZone.getOffset(System.currentTimeMillis())
        return offsetMillis / (1000 * 60 * 60) // 转换为小时
    }

    /**
     * 获取当前设备的UTC偏移量字符串
     * 例如："+08:00"、"+03:30"、"-05:00"
     * @return UTC偏移量字符串
     */
    fun getCurrentUtcOffsetString(): String {
        val timeZone = TimeZone.getDefault()
        val offsetMillis = timeZone.getOffset(System.currentTimeMillis())

        val totalMinutes = offsetMillis / (1000 * 60)
        val hours = totalMinutes / 60
        val minutes = abs(totalMinutes % 60)

        val sign = if (totalMinutes >= 0) "+" else "-"
        return String.format("%s%02d:%02d", sign, abs(hours), minutes)
    }

    /**
     * 获取当前设备的UTC偏移量（小时，支持小数）
     * 例如：东八区返回8.0，伊朗时间UTC+3:30返回3.5
     * @return UTC偏移量（小时，小数形式）
     */
    fun getCurrentUtcOffsetHours(): Double {
        val timeZone = TimeZone.getDefault()
        val offsetMillis = timeZone.getOffset(System.currentTimeMillis())
        return offsetMillis / (1000.0 * 60 * 60) // 转换为小时（小数）
    }

    /**
     * 将本地时间戳转换为UTC时间戳
     * @param localTimestamp 本地时间戳（毫秒）
     * @return UTC时间戳（毫秒）
     */
    fun convertLocalToUtc(localTimestamp: Long): Long {
        return convertTimestampBetweenTimeZones(
            localTimestamp,
            TimeZone.getDefault().id,
            "UTC"
        )
    }

    /**
     * 将UTC时间戳转换为本地时间戳
     * @param utcTimestamp UTC时间戳（毫秒）
     * @return 本地时间戳（毫秒）
     */
    fun convertUtcToLocal(utcTimestamp: Long): Long {
        return convertTimestampBetweenTimeZones(
            utcTimestamp,
            "UTC",
            TimeZone.getDefault().id
        )
    }

    /**
     * 将带有UTC偏移量的时间戳转换为目标时区的时间戳
     * @param timestamp 原始时间戳（毫秒）
     * @param utcOffset 原始时间戳的UTC偏移量（小时）
     * @param targetUtcOffset 目标时区的UTC偏移量（小时），默认为当前设备时区
     * @return 转换后的时间戳（毫秒）
     */
    fun convertTimestampWithUtcOffset(timestamp: Long, utcOffset: Int, targetUtcOffset: Int = getCurrentUtcOffset()): Long {
        // 先将时间戳转换为UTC时间
        val utcTime = timestamp - utcOffset * 60 * 60 * 1000
        // 再从UTC转换为目标时区时间
        return utcTime + targetUtcOffset * 60 * 60 * 1000
    }

    /**
     * 格式化时间戳为指定格式的字符串，考虑时区
     * @param timestamp 时间戳（毫秒）
     * @param utcOffset UTC偏移量（小时）
     * @param format 日期格式
     * @return 格式化后的时间字符串
     */
    fun formatTimestampWithUtcOffset(timestamp: Long, utcOffset: Int, format: SimpleDateFormat): String {
        val targetTimestamp = convertTimestampWithUtcOffset(timestamp, utcOffset)
        return format.format(Date(targetTimestamp))
    }

    /**
     * 解析UTC偏移字符串，返回总的分钟偏移量
     * @param utcOffsetString 格式如 "UTC+5:45", "UTC-3:30", "UTC+8:00"
     * @return 总的分钟偏移量（正数表示东时区，负数表示西时区）
     */
    private fun parseUtcOffsetToMinutes(utcOffsetString: String): Int {
        // 移除 "UTC" 前缀
        val offsetPart = utcOffsetString.removePrefix("UTC")

        // 判断正负号
        val isPositive = offsetPart.startsWith("+")
        val timeString = offsetPart.removePrefix("+").removePrefix("-")

        // 分割小时和分钟
        val parts = timeString.split(":")
        val hours = parts[0].toInt()
        val minutes = if (parts.size > 1) parts[1].toInt() else 0

        // 计算总分钟数
        val totalMinutes = hours * 60 + minutes

        return if (isPositive) totalMinutes else -totalMinutes
    }

    /**
     * 将UTC时间戳转换为指定时区的时间戳
     * @param utcTimestamp UTC时间戳（毫秒）
     * @param utcOffsetString 目标时区偏移字符串，如 "UTC+5:45"
     * @return 转换后的时间戳（毫秒）
     */
    fun convertUtcTimestampToTimezone(utcTimestamp: Long, utcOffsetString: String): Long {
        val offsetMinutes = parseUtcOffsetToMinutes(utcOffsetString)
        return utcTimestamp + offsetMinutes * 60 * 1000
    }

    /**
     * 直接从UTC时间戳获取指定时区的时间字符串
     */
    fun getTimeStringInTimezone(
        utcTimestamp: Long,
        timezoneOffset: String = getCurrentUtcOffsetString(),
        pattern: String = "yyyy-MM-dd HH:mm:ss"
    ): String {
        return formatTimestampWithTimezone(utcTimestamp, timezoneOffset, pattern)
    }

    /**
     * 将带有UTC偏移量的时间戳转换为目标时区的时间戳
     * @param timestamp 原始时间戳（毫秒）
     * @param sourceUtcOffsetString 原始时间戳的UTC偏移字符串
     * @param targetUtcOffsetString 目标时区的UTC偏移字符串，默认为当前设备时区
     * @return 转换后的时间戳（毫秒）
     */
    fun convertTimestampWithUtcOffsetString(
        timestamp: Long,
        sourceUtcOffsetString: String,
        targetUtcOffsetString: String = getCurrentUtcOffsetString()
    ): Long {
        val sourceOffsetMinutes = parseUtcOffsetToMinutes(sourceUtcOffsetString)
        val targetOffsetMinutes = parseUtcOffsetToMinutes(targetUtcOffsetString)

        // 先转换为UTC时间
        val utcTime = timestamp - sourceOffsetMinutes * 60 * 1000
        // 再转换为目标时区时间
        return utcTime + targetOffsetMinutes * 60 * 1000
    }

    /**
     * 将时间戳转换为指定时区的时间字符串
     * @param timestamp 时间戳（毫秒）
     * @param utcOffsetString 时区偏移字符串，如 "UTC+5:45"
     * @param pattern 时间格式，默认为 "yyyy-MM-dd HH:mm:ss"
     * @return 格式化的时间字符串
     */
    fun formatTimestampWithTimezone(
        timestamp: Long,
        utcOffsetString: String,
        pattern: String = "yyyy-MM-dd HH:mm:ss"
    ): String {
        val offsetMinutes = parseUtcOffsetToMinutes(utcOffsetString)
        val adjustedTimestamp = timestamp + offsetMinutes * 60 * 1000

        val sdf = SimpleDateFormat(pattern, Locale.getDefault())
        sdf.timeZone = TimeZone.getTimeZone("UTC") // 使用UTC避免二次偏移

        return sdf.format(Date(adjustedTimestamp))
    }

//    // 示例：处理尼泊尔标准时间 UTC+5:45
//    val utcTimestamp = System.currentTimeMillis() // 当前UTC时间戳
//    val nepalTimeZone = "UTC+5:45"
//
//    // 将UTC时间戳转换为尼泊尔时间戳
//    val nepalTimestamp = convertUtcTimestampToTimezone(utcTimestamp, nepalTimeZone)
//
//    // 格式化为可读时间
//    val nepalTimeString = formatTimestampWithTimezone(utcTimestamp, nepalTimeZone)
//    println("尼泊尔时间: $nepalTimeString")
//
//    // 从尼泊尔时间转换为其他时区
//    val chinaTimeZone = "UTC+8:00"
//    val chinaTimestamp = convertTimestampWithUtcOffsetString(
//        nepalTimestamp,
//        nepalTimeZone,
//        chinaTimeZone
//    )
//    val chinaTimeString = formatTimestampWithTimezone(chinaTimestamp, "UTC+0:00")
//    println("对应的中国时间: $chinaTimeString")
//
//    // 使用示例
//    val nepalTime = getTimeStringInTimezone(System.currentTimeMillis(), "UTC+5:45")
//    println("尼泊尔当前时间: $nepalTime")

    /**
     * 计算时间分界点
     * @param startTimestamp 开始时间戳（毫秒）
     * @param endTimestamp 结束时间戳（毫秒）
     * @param intervalCount 分界点数量（默认5个点）
     * @return 时间分界点列表，格式为"HH:mm:ss"
     */
    fun calculateTimeBreakpoints(
        startTimestamp: Long,
        endTimestamp: Long,
        intervalCount: Int = 5,
        outFormat:String = "%02d:%02d:%02d"
    ): List<String> {
        val breakpoints = mutableListOf<String>()

        // 计算时间间隔
        val totalDuration = endTimestamp - startTimestamp
        val interval = totalDuration / (intervalCount - 1)

        // 生成分界点
        for (i in 0 until intervalCount) {
            val timestamp = startTimestamp + (interval * i)
            val timeString = formatTimestamp(timestamp,outFormat)
            breakpoints.add(timeString)
        }

        return breakpoints
    }

    /**
     * 将时间戳格式化为HH:mm:ss格式
     * @param timestamp 时间戳（毫秒）
     * @return 格式化后的时间字符串
     */
    private fun formatTimestamp(timestamp: Long,outFormat:String): String {
        val calendar = Calendar.getInstance()
        calendar.timeInMillis = timestamp

        val hour = calendar.get(Calendar.HOUR_OF_DAY)
        val minute = calendar.get(Calendar.MINUTE)
        val second = calendar.get(Calendar.SECOND)

        return String.format(outFormat, hour, minute, second)
    }

    /**
     * 计算时间分界点（带四舍五入优化）
     * @param startTimestamp 开始时间戳（毫秒）
     * @param endTimestamp 结束时间戳（毫秒）
     * @param intervalCount 分界点数量（默认5个点）
     * @return 时间分界点列表，格式为"HH:mm:ss"，秒数>=30时四舍五入
     */
    fun calculateTimeBreakpointsRounded(
        startTimestamp: Long,
        endTimestamp: Long,
        intervalCount: Int = 5
    ): List<String> {
        val breakpoints = mutableListOf<String>()

        // 计算时间间隔
        val totalDuration = endTimestamp - startTimestamp
        val interval = totalDuration / (intervalCount - 1)

        // 生成分界点
        for (i in 0 until intervalCount) {
            val timestamp = startTimestamp + (interval * i)
            val timeString = formatTimestampRounded(timestamp)
            breakpoints.add(timeString)
        }

        return breakpoints
    }

    /**
     * 将时间戳格式化为HH:mm:ss格式（带四舍五入）
     * @param timestamp 时间戳（毫秒）
     * @return 格式化后的时间字符串，秒数>=30时四舍五入
     */
    private fun formatTimestampRounded(timestamp: Long): String {
        val calendar = Calendar.getInstance()
        calendar.timeInMillis = timestamp

        var hour = calendar.get(Calendar.HOUR_OF_DAY)
        var minute = calendar.get(Calendar.MINUTE)
        val second = calendar.get(Calendar.SECOND)

        // 秒数四舍五入逻辑
        val roundedSecond = if (second >= 30) {
            minute += 1
            if (minute >= 60) {
                minute = 0
                hour += 1
                if (hour >= 24) {
                    hour = 0
                }
            }
            0
        } else {
            0
        }

//        return String.format("%02d:%02d:%02d", hour, minute, roundedSecond)
        return String.format("%02d:%02d", hour, minute)
    }

    /**
     * 获取指定时间戳当天之后该月剩余每天的时间戳数组
     * @param timestamp 指定的时间戳（毫秒）
     * @param days 指定天数，大于0时获取指定天数的时间戳数组，否则获取该月剩余所有天数
     * @return 时间戳数组（每天的00:00:00时刻）
     *
     * // 获取当前时间戳之后该月剩余每天的00:00:00时刻 val remainingDays = TimeUtils.getRemainingDaysOfMonth(System.currentTimeMillis())
     */
    fun getRemainingDaysOfMonth(timestamp: Long, days: Int = -1): Array<Long> {
        val calendar = Calendar.getInstance()
        calendar.timeInMillis = timestamp

        val targetDays = if (days > 0) {
            // 如果指定了天数，使用指定天数
            days
        } else {
            // 否则获取该月剩余天数
            val maxDayOfMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH)
            val currentDay = calendar.get(Calendar.DAY_OF_MONTH)
            maxDayOfMonth - currentDay
        }

        // 如果没有目标天数，返回空数组
        if (targetDays <= 0) {
            return emptyArray()
        }

        val result = mutableListOf<Long>()

        // 从下一天开始，生成指定天数的时间戳
        for (i in 1..targetDays) {
            val nextDayCalendar = Calendar.getInstance()
            nextDayCalendar.timeInMillis = timestamp
            nextDayCalendar.add(Calendar.DAY_OF_MONTH, i)

            // 设置为当天的00:00:00
            nextDayCalendar.set(Calendar.HOUR_OF_DAY, 0)
            nextDayCalendar.set(Calendar.MINUTE, 0)
            nextDayCalendar.set(Calendar.SECOND, 0)
            nextDayCalendar.set(Calendar.MILLISECOND, 0)

            result.add(nextDayCalendar.timeInMillis)
        }

        return result.toTypedArray()
    }

    /**
     * 获取指定时间戳当天之后该月剩余每天的时间戳数组（重载方法，支持自定义时分秒）
     * @param timestamp 指定的时间戳（毫秒）
     * @param days 指定天数，大于0时获取指定天数的时间戳数组，否则获取该月剩余所有天数
     * @param hour 小时（0-23）
     * @param minute 分钟（0-59）
     * @param second 秒（0-59）
     * @return 时间戳数组（每天的指定时分秒时刻）
     * // 获取当前时间戳之后3天的12:30:00时刻 val next3DaysCustomTime = TimeUtils.getRemainingDaysOfMonth(System.currentTimeMillis(), 3, 12, 30, 0)
     */
    fun getRemainingDaysOfMonth(timestamp: Long, days: Int = -1, hour: Int = 0, minute: Int = 0, second: Int = 0): Array<Long> {
        val calendar = Calendar.getInstance()
        calendar.timeInMillis = timestamp

        val targetDays = if (days > 0) {
            // 如果指定了天数，使用指定天数
            days
        } else {
            // 否则获取该月剩余天数
            val maxDayOfMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH)
            val currentDay = calendar.get(Calendar.DAY_OF_MONTH)
            maxDayOfMonth - currentDay
        }

        // 如果没有目标天数，返回空数组
        if (targetDays <= 0) {
            return emptyArray()
        }

        val result = mutableListOf<Long>()

        // 从下一天开始，生成指定天数的时间戳
        for (i in 1..targetDays) {
            val nextDayCalendar = Calendar.getInstance()
            nextDayCalendar.timeInMillis = timestamp
            nextDayCalendar.add(Calendar.DAY_OF_MONTH, i)

            // 设置为指定的时分秒
            nextDayCalendar.set(Calendar.HOUR_OF_DAY, hour)
            nextDayCalendar.set(Calendar.MINUTE, minute)
            nextDayCalendar.set(Calendar.SECOND, second)
            nextDayCalendar.set(Calendar.MILLISECOND, 0)

            result.add(nextDayCalendar.timeInMillis)
        }

        return result.toTypedArray()
    }

    /**
     * 获取指定时间戳所在周的所有天的时间戳
     * @param timestamp 输入的时间戳（毫秒）
     * @return 返回该时间戳所在周的所有天的时间戳数组，从周一到周日（共7天），每个Pair包含一天的开始时间(00:00:00)和结束时间(23:59:59)
     */
    fun getWeekTimestamps(timestamp: Long): Array<Pair<Long, Long>> {
        val calendar = Calendar.getInstance()
        calendar.timeInMillis = timestamp

        // 获取当前是周几（1=周日，2=周一，...，7=周六）
        // 计算到周一的偏移量（周一为一周的开始）
        val offsetToMonday = when (calendar.get(Calendar.DAY_OF_WEEK)) {
            Calendar.SUNDAY -> -6    // 周日往前6天到周一
            Calendar.MONDAY -> 0     // 周一不需要偏移
            Calendar.TUESDAY -> -1   // 周二往前1天到周一
            Calendar.WEDNESDAY -> -2 // 周三往前2天到周一
            Calendar.THURSDAY -> -3  // 周四往前3天到周一
            Calendar.FRIDAY -> -4    // 周五往前4天到周一
            Calendar.SATURDAY -> -5  // 周六往前5天到周一
            else -> 0
        }

        // 设置到周一的00:00:00
        calendar.add(Calendar.DAY_OF_MONTH, offsetToMonday)
        calendar.set(Calendar.HOUR_OF_DAY, 0)
        calendar.set(Calendar.MINUTE, 0)
        calendar.set(Calendar.SECOND, 0)
        calendar.set(Calendar.MILLISECOND, 0)

        val result = mutableListOf<Pair<Long, Long>>()

        // 添加周一到周日的时间戳对
        for (i in 0 until 7) {
            // 获取当天的开始时间（00:00:00）
            val dayStart = calendar.timeInMillis

            // 设置为当天的结束时间（23:59:59）
            calendar.set(Calendar.HOUR_OF_DAY, 23)
            calendar.set(Calendar.MINUTE, 59)
            calendar.set(Calendar.SECOND, 59)
            calendar.set(Calendar.MILLISECOND, 999)
            val dayEnd = calendar.timeInMillis

            // 添加时间对
            result.add(Pair(dayStart, dayEnd))

            // 移动到下一天的00:00:00
            calendar.add(Calendar.DAY_OF_MONTH, 1)
            calendar.set(Calendar.HOUR_OF_DAY, 0)
            calendar.set(Calendar.MINUTE, 0)
            calendar.set(Calendar.SECOND, 0)
            calendar.set(Calendar.MILLISECOND, 0)
        }

        return result.toTypedArray()
    }

    /**
     * 根据生日日期计算年龄
     * @param birthday 生日日期字符串，格式如"1992-9-10"或"1992-09-10"
     * @return 返回年龄岁数，如果日期格式错误返回-1
     */
    fun calculateAge(birthday: String): Int {
        return try {
            // 支持多种日期格式
            val birthdayDate = when {
                birthday.matches(Regex("\\d{4}-\\d{1,2}-\\d{1,2}")) -> {
                    // 格式：yyyy-M-d 或 yyyy-MM-dd
                    val parts = birthday.split("-")
                    val year = parts[0].toInt()
                    val month = parts[1].toInt()
                    val day = parts[2].toInt()
                    Calendar.getInstance().apply {
                        set(year, month - 1, day) // Calendar的月份从0开始
                    }
                }
                else -> {
                    // 尝试使用默认格式解析
                    Calendar.getInstance().apply {
                        time = formatYearMonthDay.parse(birthday) ?: return -1
                    }
                }
            }

            val today = Calendar.getInstance()
            var age = today.get(Calendar.YEAR) - birthdayDate.get(Calendar.YEAR)

            // 检查是否还没到今年的生日
            if (today.get(Calendar.MONTH) < birthdayDate.get(Calendar.MONTH) ||
                (today.get(Calendar.MONTH) == birthdayDate.get(Calendar.MONTH) &&
                        today.get(Calendar.DAY_OF_MONTH) < birthdayDate.get(Calendar.DAY_OF_MONTH))) {
                age--
            }

            age
        } catch (e: Exception) {
            -1 // 返回-1表示日期格式错误或解析失败
        }
    }
}